<template>
    <div class="rolesTable">
        <div class="">
            <el-divider class="topLine"><i class="lineIcon el-icon-document-copy"></i><span
                    class="lineTitle">模块-角色管理表列表</span></el-divider>
        </div>

        <div class="batchOPT" v-show="getAuthorityResources('010101')">
            <el-button class="batchBTN" @click="toggleSelection([roless[1],roless[2]])">批量删除</el-button>
        </div>
        <div class="addRoles" v-show="getAuthorityResources('010101')">
            <el-button class="addBTN" type="primary" icon="el-icon-circle-plus-outline" @click="addRoles">新增
            </el-button>
        </div>
        <!--:data绑定data中预设的参数
        单行显示:show-overflow-tooltip="true"
        如果为tr，则需要v-for="(roles,index) of roless" :key="index"
        -->
        <el-table
                ref="multipleTable"
                tooltip-effect="dark"
                @selection-change="handleSelectionChange"
                :data="roless"
                :show-overflow-tooltip="true"
                border
                style="width: 100%"
                class="previous-row"
                :header-cell-style="{backgroundImage:'linear-gradient(#ff6e02,#ff6d00)',color:'#ffffff',}"
        >

            <el-table-column type="selection" width="35">
            </el-table-column>
            <el-table-column
                    sortable
                    fixed
                    prop="uniId"
                    label="唯一ID"
                    width="200"
                    :show-overflow-tooltip="true"
            >
            </el-table-column>

            <el-table-column
                    sortable
                    fixed
                    prop="name"
                    label="角色名称"

                    :show-overflow-tooltip="true"
            >
            </el-table-column>

            <el-table-column
                    sortable
                    fixed
                    prop="privilegeDesc"
                    label="权限描述"

                    :show-overflow-tooltip="true"
            >
            </el-table-column>

            <el-table-column
                    class="optionList"
                    fixed="right"
                    label="操作"
            >
                <!--使用slot-scope传递当前行参数-->
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            type="primary"
                            @click="edit(scope.row)">编辑
                    </el-button>
                    <el-button
                            size="mini"
                            type="warning"
                            @click="empPrivilege(scope.row)">权限
                    </el-button>
                    <el-button v-show="getAuthorityResources('010102')"
                            size="mini"
                            type="danger"
                            @click="del(scope.row)">删除
                    </el-button>
                </template>

            </el-table-column>
        </el-table>


        <div class="pageHelper">
            <el-button class="flushBTN" type="primary" @click="pageList(1)">刷新数据</el-button>
            <page-helper ref="pageHelper" :list="pageList"></page-helper>

        </div>

        <div class="editRoles">
            <el-dialog :visible.sync="dialogFormVisible" :close-on-click-modal="false" class="dialogDef">
                <div slot="title" class="header-title">
                    <div style="padding:15px 20px;">{{this.dialogTitle}}</div>
                </div>
                <!--绑定校验规则，必须这里:model绑定模块，ref做别名，:rules指定规则-->
                <el-form v-model="roles" :model="roles" ref="roles" :rules="rules">
                    <el-form-item :label="labelName" :label-width="formLabelWidth">
                        <el-input v-model="roles.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item :label="labelContent" :label-width="formLabelWidth">
                        <el-input v-model="roles.privilegeDesc"></el-input>
                    </el-form-item>
                    <el-form-item class="resourcesTree" v-show="roles.uniId">
                        <template>
                            <!--默认选中
                            node-key="uniId"开启node-key
                            -->
                            <ul class="infinite-list" style="overflow:auto">
                                <el-tree
                                        :data="resourcess"
                                        :props="defaultProps"
                                        :expand-on-click-node="false"
                                        node-key="uniId"
                                        show-checkbox
                                        :default-expanded-keys="checkedKeys"
                                        :default-checked-keys="checkedKeys"
                                        ref="resourcesTree">
                                    <span class="tree-node" slot-scope="{node}">
                                        <span class="nodeIcon glyphicon glyphicon-folder-open"></span>
                                        <span class="labelName">{{node.label}}</span>
                                    </span>
                                </el-tree>
                            </ul>

                        </template>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editRoles('roles')">保 存</el-button>
                </div>
            </el-dialog>
        </div>

        <div class="editRolesEmp">
            <el-dialog :visible.sync="dialogFormEmpVisible" :close-on-click-modal="false">
                <div slot="title" class="header-title">
                    <div style="padding:15px 20px;">{{this.dialogEmpTitle}}</div>
                </div>
                <!--绑定校验规则，必须这里:model绑定模块，ref做别名，:rules指定规则
                :left-default-checked="[2, 3]"
                :right-default-checked="[1]"
                :data 绑定默认数据
                -->
                <el-form v-model="roles" :model="roles" ref="rolesEmp" :rules="rules">

                    <el-form-item class="rolesEmp">
                        <template style="text-align: center">
                            <el-transfer
                                    style="text-align: left; display: inline-block"
                                    v-model="employeeIds"
                                    filterable
                                    :titles="['选择员工', '赋予权限']"
                                    :button-texts="['取消', '附权']"
                                    :right-default-checked="employeeIds"
                                    :format="{
                                                noChecked: '${total}',
                                                hasChecked: '${checked}/${total}'
                                              }"
                                    @change="handleChange"
                                    :data="employeeList">
                                <span slot-scope="{ option }">{{ option.label }}</span>
                                <i class="transfer-footer el-icon-user" slot="left-footer"><span
                                        class="transfer-footer-span">员工列表</span></i>
                                <i class="transfer-footer el-icon-user-solid" slot="right-footer"><span
                                        class="transfer-footer-span">{{roles.name}}</span></i>
                            </el-transfer>
                        </template>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormEmpVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editEmpRoles('rolesEmp')">保 存</el-button>
                </div>
            </el-dialog>
        </div>

    </div>
</template>

<script>
    import PageHelper from "../../../components/PageHelper";
    import Resources from "./Resources";

    export default {
        name: "RolesSet",
        //引用组件
        components: {PageHelper},
        data() {
            let nameValidate = (rule, value, callback) => {
                function getLength(str) {
                    //如果为中文，替换为ccc，1个中文字符计算长度=1
                    return str.replace(/[^x00-xff]/g, 'c').length;
                }

                if (value === '') {
                    callback(new Error("资源名称不能为空"));
                } else if (getLength(value) < 2) {
                    callback(new Error("资源名称长度至少3位"));
                } else {
                    callback();
                }
            };

            return {
                rules: {
                    name: [
                        {validator: nameValidate, trigger: 'blur'}
                    ],
                },
                message: '这里是大模块-角色管理表内容页',
                roless: [],
                roles: {},
                resourcess: [],
                options: VIDEO_TYPE,
                charge: VIDEO_CHARGE,
                isShow: YES_OR_NO,
                level: LEVEL,
                status: STATUS,
                //edit模态框
                dialogFormVisible: false,
                dialogType: "", //对话框类型：添加add/更新edit
                dialogTitle: '',
                labelName: '',
                disabled: 'disabled',
                labelContent: '',
                formLabelWidth: '120px',
                //资源树
                //expendedKeys: [], //tree默认展开的数组
                defaultProps: {
                    children: 'children', //子菜单的属性名
                    label: 'name' //显示的名称
                },
                checkedKeys: [], //默认选中
                checkedKeysParent: [], //回显时，如果不存在children，则将父级的uniId去除，这里存储parentId
                //保存dto数据
                resourcesId: [],
                //权限模态框
                dialogFormEmpVisible: false,
                dialogEmpType: "",
                dialogEmpTitle: "",
                employeeList: [],
                employeeIds: [],//根据roleId获取的员工ids
                empIds: [],//保存时的handleChange

            }
        },
        mounted() {
            //1.普通列表查询
            this.list();
            //自定义赋值分页每页行数
            this.$refs.pageHelper.size = 10;
            //2.分页列表查询，默认初始化执行第一页
            this.pageList(1);

        },
        methods: {
            getAuthorityResources(uniId) {
                return Tool.authorityResources(uniId);
            },
            handleChange(value, direction, movedKeys) {
                if (direction === "right") {
                    this.empIds = value;
                } else {
                    this.empIds = [];
                }
            },
            //多选的方法
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row);
                    });
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            //1.list查询
            list() {
                this.$axios.get(process.env.VUE_APP_SERVER + '/system/admin/roles/dtoList')
                    .then((response) => {
                        console.log("模块-角色管理表列表：", response);
                    })
            },
            empList() {
                this.$axios.get(process.env.VUE_APP_SERVER + '/business/admin/employee/dtoList')
                    .then((response) => {
                        let resp = response.data;
                        let emps = [];
                        for (let i = 0; i < resp.length; i++) {
                            emps.push({
                                key: resp[i].uniId,
                                label: resp[i].name,
                            })
                        }
                        this.employeeList = emps;
                    })
            },
            //2.查询当前页，需要设置变量传入pageHelper分页插件
            pageList(page) {
                Loadings.show();
                this.$axios.post(process.env.VUE_APP_SERVER + '/system/admin/roles/pageList', {
                    currentPage: page, //向后端发送参数。当前页
                    size: this.$refs.pageHelper.size, //引用传入组件后，在标签中refs定义的别名
                }).then((response) => {
                    Loadings.hide();
                    let resp = response.data;
                    this.roless = resp.responseData.listPageData;
                    this.$refs.pageHelper.render(page, resp.responseData.totalSize);

                })
            },
            //3.新增roles
            addRoles() {
                //可以在这里清空roles:this.roless=null;
                this.roles={};
                this.dialogTitle="新增角色";
                this.labelName="角色名称";
                this.labelContent="权限描述";
                let responseMsg='';
                this.dialogFormVisible=true;
                this.$axios.get(process.env.VUE_APP_SERVER + '/system/admin/resources/dtoTree')
                    .then((response) => {
                        let resp = response.data;
                        responseMsg = response;
                        Loadings.hide();
                        if (resp.success) {
                            this.resourcess = resp.responseData;
                        } else {
                            this.$notify({
                                title: '资源树获取失败，请联系管理员!',
                                message: resp.responseMsg,
                                position: "top-right",
                                type: 'warning'
                            });
                        }
                    });
            },
            //4.修改
            edit(roles) {
                /*jquery继承对象： $.extend({新对象},旧对象)
                避免vue数据绑定漏洞，更改数据时，随之更改显示的data，但实际没有进行真实保存数据库
                 */
                Loadings.show();
                this.roles = $.extend({}, roles);
                this.dialogFormVisible = true;
                this.dialogTitle = "编辑角色权限";
                this.labelName = "角色名称";
                this.labelContent = "权限表述";
                let responseMsg = '';

                this.checkedKeys = [];
                this.$axios.get(process.env.VUE_APP_SERVER + '/system/admin/rolesResources/info/' + this.roles.uniId)
                    .then((response) => {
                        let resp = response.data;
                        responseMsg = response;
                        Loadings.hide();
                        if (resp.success) {
                            let uniIds = [];
                            uniIds = resp.responseData;

                            for (let i = 0; i < uniIds.length; i++) {
                                this.checkedKeys.push(uniIds[i].resourcesId);
                            }

                        } else {
                            this.$notify({
                                title: '资源树获取失败，请联系管理员!',
                                message: resp.responseMsg,
                                position: "top-right",
                                type: 'warning'
                            });
                        }
                    });
                this.$axios.get(process.env.VUE_APP_SERVER + '/system/admin/resources/dtoTree')
                    .then((response) => {
                        let resp = response.data;
                        responseMsg = response;
                        Loadings.hide();
                        if (resp.success) {
                            this.resourcess = resp.responseData;
                            let resourcessId = [];

                            for (let i = 0; i < this.resourcess.length; i++) {
                                resourcessId.push(this.resourcess[i].uniId);
                                if (Tool.isNotEmpty(this.resourcess[i].children)) {
                                    for (let j = 0; j < this.resourcess[i].children.length; j++) {
                                        resourcessId.push(this.resourcess[i].children[j].uniId);
                                        if (Tool.isNotEmpty(this.resourcess[i].children[j].children)) {
                                            for (let r = 0; r < this.resourcess[i].children[j].children.length; r++) {
                                                if (this.checkedKeys.indexOf(this.resourcess[i].children[j].children[r].uniId) === -1) {
                                                    this.checkedKeysParent.push(this.resourcess[i].children[j].children[r].parentId);
                                                    this.checkedKeysParent.push(this.resourcess[i].children[j].parentId);

                                                    //this.checkedKeys.splice(this.checkedKeys.contains(this.resourcess[i].children[j].children[r].parentId),1);
                                                }
                                                resourcessId.push(this.resourcess[i].children[j].children[r].uniId);
                                            }
                                        }
                                    }
                                }
                            }

                            for (let i = 0; i < this.checkedKeysParent.length; i++) {
                                for (let j = 0; j < this.checkedKeys.length; j++) {
                                    if (this.checkedKeys[j]===this.checkedKeysParent[i]) {
                                        this.checkedKeys.splice(this.checkedKeys.indexOf(this.checkedKeys[j]),1);
                                    }
                                }
                            }

                        } else {
                            this.$notify({
                                title: '资源树获取失败，请联系管理员!',
                                message: resp.responseMsg,
                                position: "top-right",
                                type: 'warning'
                            });
                        }
                    });
                //Loadings.show();
                /**打开先清空选中，否则，再次打开默认选中上一次
                 * 注意，在请求发送之前清空，如果一进入edit方法就清空，请求延迟时，会无checkedKeys，空白选择框
                 * */

            },
            editRoles(formName) {
                let responseMsg = '';
                //注意，在发送请求之前，组装resourcesId时，先清空，否则会计入上一次存储的resourcesId
                this.resourcesId = [];
                //getCheckednodes：(leafOnly, includeHalfChecked) 接收两个 boolean 类型的参数，
                // 1. 是否只是叶子节点，默认值为 false 2. 是否包含半选节点，默认值为 false ，这里我们保存连同半叶
                let leafNodes = this.$refs.resourcesTree.getCheckedNodes(false, true);
                for (let i = 0; i < leafNodes.length; i++) {
                    this.resourcesId.push(leafNodes[i].uniId);
                }
                //前端校验
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$axios.post(process.env.VUE_APP_SERVER + '/system/admin/roles/save/rolesResources', {
                            uniId: this.roles.uniId || '',
                            name: this.roles.name,
                            privilegeDesc: this.roles.privilegeDesc,
                            resourcesId: this.resourcesId
                        })
                            .then((response) => {
                                let resp = response.data;
                                responseMsg = response;
                                if (resp.success) {
                                    //关闭对话框
                                    this.dialogFormVisible = false;
                                    this.pageList(1);
                                    toast.success("保存成功", "bottom-end");
                                } else {
                                    this.$notify({
                                        title: '填写内容错误',
                                        message: resp.responseMsg,
                                        position: "top-right",
                                        type: 'warning'
                                    });
                                }
                            })
                    } else {
                        this.$notify({
                            title: '填写内容错误',
                            message: '请按照提示内容填写正确信息',
                            position: "top-right",
                            type: 'warning'
                        });
                        return false;
                    }
                })
            },
            empPrivilege(roles) {
                this.dialogFormEmpVisible = true;
                Loadings.show();
                this.dialogEmpTitle = "员工角色配置";
                this.empList();
                this.roles = $.extend({}, roles);
                this.$axios.post(process.env.VUE_APP_SERVER + '/system/admin/rolesEmployee/info/' + this.roles.uniId)
                    .then((response) => {
                        Loadings.hide();
                        let resp = response.data;
                        let empData = [];
                        if (resp.success) {
                            for (let i = 0; i < resp.responseData.length; i++) {
                                empData.push(resp.responseData[i].employeeId);
                            }
                            this.employeeIds = empData;
                        }
                    })
            },
            editEmpRoles(formName) {
                if (Tool.isNotEmpty(this.empIds)) {
                    this.$axios.post(process.env.VUE_APP_SERVER + '/system/admin/roles/save/rolesEmployee',
                        {
                            uniId: this.roles.uniId,
                            employeeId: this.empIds,
                        }).then((response) => {
                        let resp = response.data;
                        this.dialogFormEmpVisible = false;
                        toast.success("保存成功", "bottom-end");
                    })
                }
            },
            del(roles) {
                /**
                 * 前端=》路径内携带参数使用url：'../'+{param}
                 * 后端=》requestMapping('../{param}')
                 *       void ...(@PathVariable String {param})
                 *
                 * ***引用toast的showConfirm全局方法，需要定义局部变量_this
                 * ***并且将存入的roles转化为局部对象，才能获取到uniId
                 */
                let _this = this;
                let rolesParam = roles;
                toast.showConfirm(roles.name, function () {
                        _this.$axios.delete(process.env.VUE_APP_SERVER + '/system/admin/roles/del/' + rolesParam.uniId)
                            .then((response) => {
                                let resp = response.data;
                                if (resp.success) {
                                    _this.pageList(1);
                                }else{
                                    this.$notify({
                                        title:'非法操作会被锁定IP，请停止！',
                                        message:resp.responseMsg,
                                        position:'top-right',
                                        type:'warning'
                                    })
                                }
                            })

                    }
                )
            },
            //更新显示show
            updateShow(row) {
                this.roles = row;
                let responseMsg = '';
                //前端校验
                this.$axios.post(process.env.VUE_APP_SERVER + '/system/admin/roles/save', this.roles)
                    .then((response) => {
                        let resp = response.data;
                        responseMsg = response;

                        if (resp.success) {
                            this.pageList(1);
                            //引入全局变量toast提示
                            toast.success("保存成功", "bottom-end");
                        } else {
                            this.$notify({
                                title: '修改失败，请联系管理员!',
                                message: resp.responseMsg,
                                position: "top-right",
                                type: 'warning'
                            });
                        }
                    });
            },
        }
    }
</script>

<style scoped>
    /*顶部line样式*/
    .topLine {
        background-color: #2a92ee;
    }

    .lineIcon {
        font-size: 22px;
        color: #2a92ee;
        position: relative;
    }

    .lineTitle {
        position: relative;
        font-size: 16px;
        color: #2a92ee;
    }

    /*table样式*/
    .previous-row {
        background: #f0f9eb;
        margin-left: 2%;
        max-width: 96%;

    }

    .optionList {
        text-align: center;
    }

    /deep/ .el-table td, .el-table th {
        padding: 5px 0;
        text-align: center;
    }

    /deep/ .el-table .cell {
        padding-right: 2px;
        line-height: 20px;
        text-align: center;
    }

    /deep/ .el-table .cell, .el-table--border td:first-child .cell, .el-table--border th:first-child .cell {
        padding-left: 5px;
    }

    /*批量操作*/
    .batchOPT {
        float: left;
        margin-left: 2%;
        margin-bottom: 1%;
        z-index: 1;
    }

    /*新增*/
    .addRoles {
        float: left;
        margin-left: 5px;
    }

    .addBTN {
        font-size: 16px;
        padding: 11px 20px;
        border: 1px solid white;
        box-shadow: 1px 2px 2px #409eff;
        margin-top: 0;
    }

    .batchBTN {
        background-color: #ff5202;
        color: white;
        box-shadow: 1px 2px 2px #ff6e02;
    }

    .batchBTN:hover {
        background-color: #ff3d02;
        color: white;
    }

    .batchBTN:focus {
        background-color: #ff3d02;
        color: #ffffff;
    }

    /**分页位置/
     */
    .pageHelper {
        margin-left: 60px;
    }

    .flushBTN {
        position: relative;
        float: left;
        max-width: 95px;
        margin-right: 20px;
        margin-top: 5px;
    }

    /*模态框*/
    .header-title {
        background: #2589e7;
        color: white;
        font-size: 20px;
    }
    /*限制模态框高度*/
    /*.dialogDef{
        height: 100%;
    }*/

    /deep/ .el-dialog__header {
        padding: 0;
    }

    /deep/ .el-dialog--center .el-dialog__body {
        background: #d2d3d04d;
    }

    /deep/ .el-dialog__headerbtn .el-dialog__close {
        color: white;
        font-size: 24px;
    }

    /deep/ .el-form-item__label {
        text-align: center;
        padding: 0;
    }

    /deep/ .el-input .el-input__inner {
        margin-left: -40px;
    }

    /deep/ .el-input__suffix {
        right: 35px;
    }

    /deep/ .el-dialog__body {
        padding: 20px 10px;
    }

    /deep/ .el-form-item {
        margin-bottom: 5px;
    }

    /*树型控件*/
    /deep/ .el-tree-node__content {
        height: 30px;
    }

    .resourcesTree {
        margin-top: 10px;
        margin-left: 100px;
    }

    .nodeIcon {
        margin-right: 15px;
        color: #2a92ee;
        font-size: 15px;
    }

    .labelName {
        margin-right: 30px;
        font-size: 15px;
    }

    /*权限管理*/
    /deep/ .el-transfer__buttons {
        padding: 10px 10px;
    }

    /*取消编辑框高度*/
    /deep/ .el-transfer-panel__body {
        height: 350px;
    }

    /deep/ .el-transfer-panel__list.is-filterable {
        height: 100%;
    }

    /deep/ .el-transfer-panel .el-transfer-panel__footer {
        background: #2a92ee;
        text-align: center;
        position: relative;
    }

    /*搜索*/
    /deep/ .el-transfer-panel__filter {
        margin-left: 40px;
    }

    .transfer-footer {
        color: white;
        font-size: 16px;
    }

    .transfer-footer-span {
        margin-left: 5px;
    }
</style>